import React, { useRef, useState, useEffect } from 'react';

const LazyImage = ({ src, alt, ...props }: any) => {
  const imgRef = useRef<HTMLImageElement | null>(null);
  const [inView, setInView] = useState(false);

  useEffect(() => {
    const observer = new window.IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          setInView(true);
          observer.disconnect();
        }
      },
      { threshold: 0.1 }
    );
    if (imgRef.current) {
      observer.observe(imgRef.current);
    }
    return () => {
      observer.disconnect();
    };
  }, []);

  return (
    <div {...props}>
      {inView ? (
        <img ref={imgRef} src={src} alt={alt} className='w-full object-cover' />
      ) : (
        <span ref={imgRef}></span>
      )}
    </div>
  );
};

export default LazyImage;